//
//  ViewController.swift
//  TFCollectionViewDemo
//
//  Created by Andney Jack on 2021/6/20.
//

import TFCollectionViewColumnLayout
import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var flowLayout: TFCollectionViewColumnLayout!
    @IBOutlet weak var collectionView: UICollectionView!
    var dataList = [[CGFloat]]()

    override func viewDidLoad() {
        super.viewDidLoad()

        flowLayout.allowUseSafeAreaInsets = true
        flowLayout.itemRenderDirection = .columnFirst
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }

        collectionView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 50, right: 0)

        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: TFCollectionElementKindSectionHeader, withReuseIdentifier: "section_header")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: TFCollectionElementKindSectionHeader, withReuseIdentifier: "section")

        reloadData()
    }

    func reloadData() {
        dataList.removeAll()

        for i in 0 ..< 4 {
            var cellHeights = [CGFloat]()
            let cellCount = i > 0 ? max(arc4random() % 30, 10) : max(arc4random() % 20, 1)

            for _ in 0 ..< cellCount {
                cellHeights.append(CGFloat(80 + arc4random() % 200))
            }

            dataList.append(cellHeights)
        }

        collectionView.reloadData()
    }

    @IBAction func buttonClick(_ sender: UIButton) {
        if sender.currentTitle == "ScrollTo" {
            let section = Int(arc4random()) % collectionView.numberOfSections
            let item = Int(arc4random()) % collectionView.numberOfItems(inSection: section)

            collectionView.scrollToItem(at: IndexPath(item: item, section: section), at: .top, animated: true)

        } else if sender.currentTitle == "Refresh" {
            reloadData()
        }
    }
}

extension ViewController {
    public func randomColor() -> UIColor {
        return UIColor(red: CGFloat(arc4random() % 256) / 255.0, green: CGFloat(arc4random() % 256) / 255.0, blue: CGFloat(arc4random() % 256) / 255.0, alpha: 1.0)
    }
}

extension ViewController: TFCollectionViewDelegateColumnLayout, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return dataList.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList[section].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        cell.contentView.backgroundColor = randomColor()

        var textLabel = cell.contentView.viewWithTag(1) as? UILabel
        if textLabel == nil {
            textLabel = UILabel()
            textLabel?.tag = 1
            textLabel?.font = .systemFont(ofSize: 15)
            textLabel?.textColor = .white
            textLabel?.textAlignment = .center
            textLabel?.numberOfLines = 2
            cell.contentView.addSubview(textLabel!)

            textLabel?.translatesAutoresizingMaskIntoConstraints = false
            textLabel?.centerXAnchor.constraint(equalTo: cell.contentView.centerXAnchor).isActive = true
            textLabel?.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor).isActive = true
        }

        textLabel?.text = "section: \(indexPath.section + 1)\nitem: \(indexPath.item + 1)"

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == TFCollectionElementKindSectionHeader {
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "section_header", for: indexPath)
            headerView.backgroundColor = randomColor()

            var titleLabel = headerView.viewWithTag(1) as? UILabel
            if titleLabel == nil {
                titleLabel = UILabel()
                titleLabel?.tag = 1
                titleLabel?.font = .systemFont(ofSize: 15)
                titleLabel?.textColor = .white
                titleLabel?.textAlignment = .center
                titleLabel?.numberOfLines = 2
                headerView.addSubview(titleLabel!)

                titleLabel?.translatesAutoresizingMaskIntoConstraints = false
                titleLabel?.leftAnchor.constraint(equalTo: headerView.leftAnchor, constant: 20).isActive = true
                titleLabel?.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
            }

            titleLabel?.text = "section header: \(indexPath.section + 1)"
            return headerView
        }

        return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "section", for: indexPath)
    }

    func collectionView(_ collectionView: UICollectionView, layout: TFCollectionViewColumnLayout, columnCountForSection section: Int) -> Int {
        return section % 2 > 0 ? 2 : 3
    }

    func collectionView(_ collectionView: UICollectionView, layout: TFCollectionViewColumnLayout, sizeForItemAt indexPath: IndexPath, columnWidth: CGFloat) -> CGSize {
        return CGSize(width: columnWidth, height: dataList[indexPath.section][indexPath.item])
    }

    func collectionView(_ collectionView: UICollectionView, layout: TFCollectionViewColumnLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    }

    func collectionView(_ collectionView: UICollectionView, layout: TFCollectionViewColumnLayout, insetForHeaderInSection section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
    }

    func collectionView(_ collectionView: UICollectionView, layout: TFCollectionViewColumnLayout, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }

    func collectionView(_ collectionView: UICollectionView, layout: TFCollectionViewColumnLayout, itemRenderDirectionForSectionAt section: Int) -> TFCollectionViewItemRenderDirection {
        if section % 2 > 0 {
            return .columnFirst
        } else {
            return .shortestFirst
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout: TFCollectionViewColumnLayout, shouldPinToVisibleBoundsForSupplementaryViewOfKind kind: String, section: Int) -> Bool {
        if kind == TFCollectionElementKindSectionHeader && section >= 0 {
            return true
        }
        return false
    }
}
